<template>
  <div>
    <h1 class="con-right-title">用户分组管理</h1>

    <!-- 顶部搜索 -->
    <div class="search-row search-box">
      <el-form :inline="true" :model="searchParams" class="demo-form-inline">
        <el-form-item label="分组名称">
          <el-input
            v-model="searchParams.name"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="启用状态">
          <el-select
            v-model="searchParams.groupStatus"
            placeholder="请选择"
            style="width:150px;"
            clearable
            filterable
          >
            <el-option
              v-for="item in enabled"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="创建方式">
          <el-select
            v-model="searchParams.groupCreationType"
            placeholder="请选择"
            style="width:150px;"
            clearable
            filterable
          >
            <el-option
              v-for="item in createWay"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="更新方式">
          <el-select
            v-model="searchParams.updateMethod"
            placeholder="请选择"
            style="width:150px;"
            clearable
            filterable
          >
            <el-option
              v-for="item in updateWay"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="最后计算状态">
          <el-select
            v-model="searchParams.finalCalculationStatus"
            placeholder="请选择"
            style="width:150px;"
            clearable
            filterable
          >
            <el-option
              v-for="item in calcStatus"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="创建人">
          <el-select
            v-model="searchParams.createdUser"
            placeholder="请选择"
            style="width:150px;"
            clearable
            filterable
          >
            <el-option
              v-for="item in creaters"
              :key="item.dapengUserId"
              :label="item.nickname"
              :value="item.dapengUserId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="success" icon="el-icon-search" @click="handleSearch"
            >查询</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button type="success" plain @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--table 刷新-->
    <div class="table-conBtn">
      <el-button type="success" icon="el-icon-plus" @click="handleAppend"
        >创建分群</el-button
      >
      <freshCom @searchList="searchList"></freshCom>
    </div>

    <!--table 列表-->
    <div class="table-box">
      <el-table
        v-loading="loading"
        ref="table"
        :data="tableData"
        :fit="true"
        max-height="490"
        @sort-change="handleSort"
        stripe
      >
        <el-table-column type="index" label="序号">
          <template slot-scope="scope">
            {{
              scope.$index
                | filterPage(pagingParams.pageNum, pagingParams.pageSize)
            }}
          </template>
        </el-table-column>

        <el-table-column label="分组名称" prop="name" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="人数"
          prop="totalNumber"
          align="center"
          sortable="custom"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.totalNumber }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="创建方式"
          prop="groupCreationType"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.groupCreationType | createWayFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column label="更新方式" prop="updateMethod" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.updateMethod | updateWayFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="最后计算状态"
          prop="finalCalculationStatus"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.finalCalculationStatus | calcStatusFilter
            }}</span>
          </template>
        </el-table-column>

        <el-table-column label="启用状态" prop="groupStatus" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.groupStatus"
              active-color="#1dc8a4"
              @change="handleSwitch(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          prop="createdTime"
          align="center"
          sortable="custom"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.createdTime | timeToTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建人" prop="createdUser" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createdUser.userName || '---' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <span class="button-space">
              <el-button type="text" @click="handleEdit(scope.row)">
                编辑
              </el-button>
            </span>

            <span class="button-space">
              <el-button type="text" @click="handleDetails(scope.row)">
                详情
              </el-button>
            </span>

            <span class="button-space">
              <el-button type="text" @click="exportRoles(scope.row)">
                导出
              </el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-全局组件-->
    <pageCom
      :searchParams="pagingParams"
      :total="total"
      @searchList="searchList"
    ></pageCom>

    <!-- 关闭问卷 确认弹框 -->
    <el-dialog
      title="选择创建用户分组方式"
      :visible.sync="createDialog.visible"
      width="25%"
      custom-class="custom-dialog"
    >
      <div class="dialog-container">
        <div
          class="menu-card"
          v-permission="'wh:newUserGroup:RULE'"
          @click="handleEnter('RULE')"
        >
          <div class="menu-card-title">按规则创建</div>
          <div class="menu-card-desc">
            根据用户属性、用户行为数据的筛选条件创建用户分组
          </div>
        </div>

        <div
          class="menu-card"
          v-permission="'wh:newUserGroup:DP'"
          @click="handleEnter('DP')"
        >
          <div class="menu-card-title">导入用户dp号创建</div>
          <div class="menu-card-desc">根据导入的用户大鹏号创建用户分组</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDpNum } from '@/api/system/user'
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { userGroupList, enabled, disabled, dpaccount } from '@/api/userGroup'
import { Message } from 'element-ui'

const createWayDic = {
  RULE: { text: '规则创建' },
  DP: { text: '导入创建' }
}

const updateWayDic = {
  AUTO: { text: '自动更新' },
  MANUAL: { text: '手动更新' }
}

const calcStatusDic = {
  SUCCESS: { text: '成功' },
  FAIL: { text: '失败' },
  CALCULATING: { text: '计算中' }
}

const sortDic = {
  createdTimeascending: { text: 'CREATEDTIME_ASC' },
  createdTimedescending: { text: 'CREATEDTIME_DESC' },
  totalNumberascending: { text: 'TOTALNUMBER_ASC' },
  totalNumberdescending: { text: 'TOTALNUMBER_DESC' }
}

export default {
  name: 'userGroupManage',
  msg: '用户分组管理',
  data() {
    return {
      total: 0,
      loading: true,
      tableData: [],

      enabled: [], // 启用状态
      createWay: [], // 创建方式
      updateWay: [], // 更新方式
      calcStatus: [], // 计算状态
      creaters: [], // 创建人
      // userAttrs: [], // 用户属性

      searchParams: {
        sort: '', // 排序规则
        name: '', // 用户分组名称
        groupStatus: '', // 用户分组状态
        createdUser: '', // 用户分组创建人
        groupCreationType: '', // 用户分组创建类型
        updateMethod: '', // 用户分组更新方式
        finalCalculationStatus: '', // 用户分组最终计算状态,
        activateSMSNumber: '', // 发送短信激活次数
        activateSMSEndTime: '', // 最后一次激活短信时间
        endInputTime: '', // 最后一次入量时间
        auditionSessionsNumber: '', // 试听课节数
        inputNumber: '', // 入量次数
        endActiveDate: '', // 最后活跃日期
        endrecallDate: '', // 最后召回日期
        userProperties: '' // 用户属性
      },

      pagingParams: {
        pageNum: 1,
        pageSize: 10
      },

      createDialog: {
        visible: false
      }
    }
  },

  filters: {
    createWayFilter(type) {
      return createWayDic[type].text
    },

    updateWayFilter(type) {
      return updateWayDic[type].text
    },

    calcStatusFilter(type) {
      return calcStatusDic[type].text
    }
  },

  async created() {
    // 启用状态
    const data1 = await sysNormalDisable('user_group_status')
    this.enabled = this.enabled.concat(data1)

    // 创建方式
    const data2 = await sysNormalDisable('user_group_creation_type')
    this.createWay = this.createWay.concat(data2)

    // 更新方式
    const data3 = await sysNormalDisable('user_group_update_method')
    this.updateWay = this.updateWay.concat(data3)

    // 计算状态
    const data4 = await sysNormalDisable('user_group_final_calculation_status')
    this.calcStatus = this.calcStatus.concat(data4)

    // 创建人
    await getDpNum({ type: 'OPERATORS' }, (response) => {
      this.creaters = this.creaters.concat(response)
    })
  },

  mounted() {
    this.searchList()
  },

  methods: {
    // 查询分组列表
    searchList() {
      this.loading = true

      let params = { ...this.pagingParams, ...this.searchParams }

      userGroupList(
        params,
        (res) => {
          this.total = res.total
          this.tableData = res.rows
          this.loading = false
        },
        (err) => {
          this.$message({
            message: err.message,
            type: 'warning'
          })
        }
      )
    },

    // 排序
    handleSort(column) {
      const { prop, order } = column

      if (order) {
        const key = sortDic[prop + order].text
        this.searchParams.sort = key
        this.searchList()
      }
    },

    // 启用、关闭
    handleSwitch(row) {
      if (row.groupStatus) {
        enabled(
          row.id,
          {},
          (res) => {
            // ……
          },
          (err) => {
            this.$message({
              message: err.message,
              type: 'warning'
            })
          }
        )
      }

      if (!row.groupStatus) {
        disabled(
          row.id,
          {},
          (res) => {
            // ……
          },
          (err) => {
            this.$message({
              message: err.message,
              type: 'warning'
            })
          }
        )
      }
    },

    // 打开弹框
    handleAppend() {
      this.createDialog.visible = true
    },

    // 进入指定页面
    handleEnter(e) {
      const page = e

      this.$router.push({
        name: `wh:newUserGroup:${page}`,
        query: { pageType: 'add' }
      })

      this.createDialog.visible = false
    },

    /* 编辑 */
    handleEdit(item) {
      this.$router.push({
        name: `wh:newUserGroup:${item.groupCreationType}`,
        query: { pageType: 'edit', id: item.id }
      })
    },

    /* 查看详情 */
    handleDetails(item) {
      this.$router.push({
        name: `wh:newUserGroup:${item.groupCreationType}`,
        query: { pageType: 'preview', id: item.id }
      })
    },

    // 重置
    handleReset() {
      // this.searchParams.sort = ''
      this.searchParams.name = ''
      this.searchParams.createdUser = ''
      this.searchParams.finalCalculationStatus = ''
      this.searchParams.groupCreationType = ''
      this.searchParams.groupStatus = ''
      this.searchParams.updateMethod = ''
    },

    // 查询
    handleSearch() {
      this.pagingParams.pageNum = 1
      /*
        处理时间格式
        this.searchParams.activateSMSEndTime
      */
      this.searchList()
    },

    /* 换页 */
    changePage(page) {
      this.pagingParams.pageNum = page
      this.searchList()
    },

    /* 刷新列表 */
    refresh() {
      this.searchList()
    },

    // 导出方法
    exportRoles(row) {
      this.$confirm('确定导出计算出的用户吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.$store.state.userGroup.deriveState) {
          let url = dpaccount(row.id)
          let params = { groupName: row.name }
          this.downFile('get', url, params, row.name)
          this.$store.commit('userGroup/updateDeriveState', false)
        } else {
          Message.warning('等待数据加载完成后，再导出其他数据')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.table-box .button-space {
  margin-left: 5px;
}

:deep(.custom-dialog) {
  min-height: 310px;
}

.dialog-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.dialog-container .menu-card {
  width: 80%;
  height: 100px;
  padding: 15px;
  cursor: pointer;
  border: 1px solid #ededed;

  & .menu-card-title {
    font-size: 20px;
    font-weight: 600;
    color: #000000;
  }

  & .menu-card-desc {
    font-size: 15px;
    font-weight: 500;
    color: #161616;
  }

  &:last-child {
    margin-top: 20px;
  }

  &:active {
    border: 2px solid rgb(52, 240, 52);
  }
}

:deep(.el-input input::-webkit-outer-spin-button),
:deep(.el-input input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}
:deep(.el-input input[type='number']) {
  -moz-appearance: textfield;
}
:deep(.el-input .el-input__inner) {
  line-height: 1px !important;
}
</style>
